import React, { Component } from 'react';
import { connect } from 'react-redux'
import { List, Stepper } from 'antd-mobile'
import { ADD_CAR_ITEM, SUB_CAR_ITEM } from '../../store/reducer'
class Index extends Component {
	handleCountChange = (value, v) => {
		if(value > v.count) {
			// 点击了+
			this.props.dispatch({ type: ADD_CAR_ITEM, payload: v })
		} else {
			// 点击了-
			this.props.dispatch({ type: SUB_CAR_ITEM, payload: v })
		}
	}
	render() {
		const { car } = this.props
		return (
			<div>
				<List>
					{
						car.length > 0 && car.map(v => {
							return <List.Item
								key={v.id}
								prefix={<img src={v.url}></img>}
								description={v.desc}
							>
								<p>
									<Stepper
										value={v.count}
										onChange={ (value) => this.handleCountChange(value, v) }
										min={ 1 }
									/>
								</p>
								<h4 style={{ color: 'red' }}>￥{ v.price }</h4>
							</List.Item>
						})
					}
				</List>
				<h1>总价：{  car.reduce((p, n) => p + n.price * n.count, 0)  }</h1>
			</div>
		);
	}
}

const mapState = state => {
	return {
		car: state.car
	}
}

const mapDiapatch = dispatch => {
	return {
		dispatch
	}
}
export default connect(mapState, mapDiapatch)(Index);
